package com.xry.test1.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xry.test1.dao.BellRepository;
import com.xry.test1.dao.GasRepository;
import com.xry.test1.model.DoorBellData;
import com.xry.test1.model.GasData;
import com.xry.test1.service.IHomeService;
import com.xry.test1.service.MQTTSubscriber.MQTTSubscribe;
import com.xry.test1.service.MQTTSubscriber.MqttMessageHandler;
import jakarta.annotation.PostConstruct;
import org.antlr.v4.runtime.misc.LogManager;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class DoorBellServiceImpl implements IHomeService, MqttMessageHandler {
    //数据库
    @Autowired
    private BellRepository bellRepository;
    @Autowired
    private SimpMessagingTemplate messagingTemplate; // WebSocket 消息推送

    @Autowired
    private MQTTSubscribe mqttSubscribe; // MQTT 订阅

    private static final String DOORBELL_TOPIC = "access_control";
    // 只订阅 门铃 主题

    @PostConstruct
    public void init() {
        mqttSubscribe.subscribeToTopic(DOORBELL_TOPIC,this);
    }

    public void handleIncomingMessage(String topic, MqttMessage message) {
        if (!DOORBELL_TOPIC.equals(topic)) {
            return; // 过滤掉非 kitchenGas 的消息
        }
        DoorBellData doorBellData = new DoorBellData();
        doorBellData.setRing(true);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        doorBellData.setDate(LocalDateTime.now().format(formatter));
        System.out.println(doorBellData.getDate());

        //mysql
        bellRepository.save(doorBellData);



        messagingTemplate.convertAndSend("/topic/doorBell", doorBellData);
    }
}
